<?php
namespace app\material\model;
use app\BaseModel;
use think\facade\Db;



class File extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_material_file';


    protected $append = [

        'company',

        'folder_name'

    ];


    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2021-07-06 15:04
     */
    public function getUseImgsAttr($value,$data){

        if (!empty($value)) {

            return explode(',', $value);

        }

    }
    /**
     * @author chenniang
     * @DataTime: 2021-06-29 16:33
     * @功能说明:
     */
    public function getImgsAttr($value,$data)
    {

        if (!empty($data['imgs'])) {

            return explode(',', $data['imgs']);

        }
    }




        /**
     * @author chenniang
     * @DataTime: 2021-06-24 16:50
     * @功能说明:公司
     */
    public function getCompanyAttr($value,$data){

        if(!empty($data['id'])&&isset($data['is_company'])&&!empty($data['uniacid'])){

            $company_model = new FileCompany();

            if($data['is_company']==1){
                //所有的公司
                $list = $company_model->getCompanyIds(['uniacid'=>$data['uniacid'],'status'=>1]);

            }else{
                //选中的公司
                $dis = [

                    'a.uniacid' => $data['uniacid'],

                    'a.file_id' => $data['id'],

                    'b.status'  => 1,

                ];

                $list = $company_model->getId($dis);

            }

            return $list;

        }


    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-24 16:58
     * @功能说明:文件夹名字
     */
    public function getFolderNameAttr($value,$data){

        if(!empty($data['folder_id'])){

            $folder_model = new Folder();

            return $folder_model->where(['id'=>$data['folder_id']])->value('title');
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:00
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        if(isset($data['company'])){

            $company = $data['company'];

            unset($data['company']);
        }
        //获取文件大小
        if(empty($data['file_max'])&&!empty($data['link'])&&!empty($data['file_type'])&&in_array($data['file_type'],[4,5,6])){

            $arr = $this->myGetImageSize($data['link'],'fread',true);


            if(is_array($arr)&&!empty($arr['size'])){

                $data['file_max'] = $arr['size'];
            }

        }

        if(!in_array($data['file_type'],[4,5])){

            $img = transImagesOne([$data['link']],['link'],$data['uniacid']);

            $data['link'] = $img[0];
        }
        //base64转图片
        if(isset($data['use_imgs'])&&isset($data['uniacid'])){

//            $file_arr = $this->base64ToPng($data['use_imgs']);

            $data['use_imgs'] = !empty($data['use_imgs'])?implode(',',$data['use_imgs']):'';

            $data = transImages($data,['use_imgs'],',',$data['uniacid']);

            $data['use_imgs'] = !empty($data['use_imgs'])?implode(',',$data['use_imgs']):'';

        }else{

            $data['use_imgs'] = '';
        }

        $res = $this->insert($data);

        if(!empty($company)){

            $id  = $this->getLastInsID();

            $this->updateSome($id,$data['uniacid'],$company);
        }


        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-07 15:22
     * @功能说明:base64转图片
     */
    public function base64ToPng($list){

        if(!empty($list)){

            $path = MATER_UPLOAD_PATH.date('Y-m-d',time()).'/img';

            if (!file_exists($path)){

                mkdir ($path,0777,true);
            }

            foreach ($list as $v){

                if (strpos($v, 'https://') !== false) {

                    $file_arr[] = $v;

                } else {

                    if (strstr($v,",")){

                        $v = explode(',',$v);

                        $v = $v[1];
                    }

                    $imageName = "/25220_".date("His",time())."_".rand(1111,9999).'.jpg';

                    file_put_contents($path.$imageName, base64_decode($v));

                    $file = str_replace(FILE_UPLOAD_PATH,HTTPS_PATH,$path.$imageName);

                    $file_arr[] = $file;
                }

            }

            return $file_arr;

        }

        return [];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:03
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $data['update_time'] = time();

        if(isset($data['company'])){

            $company = $data['company'];

            unset($data['company']);

            $this->updateSome($dis['id'],$data['uniacid'],$company);
        }

        if(empty($data['file_max'])&&!empty($data['link'])&&!empty($data['file_type'])&&in_array($data['file_type'],[4,5])){

            $arr = $this->myGetImageSize($data['link'],'fread',true);

            if(is_array($arr)&&!empty($arr['size'])){

                $data['file_max'] = $arr['size'];
            }

        }

        if(!empty($data['file_type'])&&!in_array($data['file_type'],[4,5])){

            $img = transImagesOne([$data['link']],['link'],$data['uniacid']);

            $data['link'] = $img[0];

            //dump($data);exit;

        }

        if(isset($data['use_imgs'])&&isset($data['uniacid'])){

//            $file_arr = $this->base64ToPng($data['use_imgs']);

            $data['use_imgs'] = !empty($data['use_imgs'])?implode(',',$data['use_imgs']):'';

            $data = transImages($data,['use_imgs'],',',$data['uniacid']);

            $data['use_imgs'] = !empty($data['use_imgs'])?implode(',',$data['use_imgs']):'';
        }

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @param $url
     * @param string $user
     * @param string $pw
     * @功能说明:获取文件大小
     * @author chenniang
     * @DataTime: 2021-07-09 13:43
     */
public function myGetImageSize($url,$user='',$pw='')
    {
        ob_start();
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        if (!empty($user) && !empty($pw))
        {
            $headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        $okay = curl_exec($ch);
        curl_close($ch);
        $head = ob_get_contents();
        ob_end_clean();

        //echo '<br>head-->'.$head.'<----end <br>';

        $regex = '/Content-Length:\s([0-9].+?)\s/';
        $count = preg_match($regex, $head, $matches);
        $size['size'] = isset($matches[1])?$matches[1]:'unknown';
        //$last=round($size/(1024*1024),3);
        //return $last.' MB';
        return $size;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-24 15:53
     * @功能说明:添加公司
     */
    public function updateSome($id,$uniacid,$company){

        $company_model = new FileCompany();

        $company_model->where(['file_id'=>$id])->delete();

        $company = $company_model->changeData($company);

        if(!empty($company)){

            foreach ($company as $value){

                $insert = [

                    'uniacid' => $uniacid,

                    'file_id' => $id,

                    'company_id' => $value
                ];

                $company_model->dataAdd($insert);

            }

        }

        return true;


    }

    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:04
     * @功能说明:详情
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }




    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:05
     * @功能说明:
     */
    public function dataList($dis,$page=10){

        $data = $this->alias('a')
            ->join('longbing_card_material_file_company b','b.file_id = a.id','left')
            ->where($dis)
            ->field('a.*')
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-29 14:57
     * @功能说明:
     */
    public function folderOrFileList($dis,$where,$map=[],$user_id = 0){

        $folder_model = new Folder();

        $a =$folder_model->where('status','=',1)->where($where)->count();


        $b = $this->where($dis)->where(function ($query) use ($map) {
            $query->whereOr($map);
        })->where('status','=',1)->count();


        $all_count = $a+$b;

        $a = $folder_model->field(['id','title','create_time','null as file_type','null as file_max','f_type','null as link','update_time'])->where('status','=',1)->where($where)->order('update_time desc,id desc')->buildSql();

        $data = $this->where($dis)->where(function ($query) use ($map) {
            $query->whereOr($map);
        })->field(['id','title','create_time','file_type','file_max','f_type','link','update_time'])->unionAll([$a])->where('status','=',1)->order('update_time desc,id desc')->paginate(10,$all_count)->toArray();


        if(!empty($data['data'])){

            $collect_model = new FileCollect();

            foreach ($data['data'] as &$v){
                //文件
                if($v['f_type']==1){
                    //文件大小
                    $v['file_max'] = getRangeMemKb(0,$v['file_max']);

                    if(!empty($user_id)){

                        $dis = [

                            'file_id' => $v['id'],

                            'user_id' => $user_id
                        ];

                        $collect = $collect_model->dataInfo($dis);

                        $v['is_collect'] = !empty($collect)?1:0;

                    }

                }else{
                    //文件夹下面有多少文件
                    $v['file_count'] = $folder_model->getUnderFileCount($v['id'],$map);

                }

                $v['create_time'] = date('m-d H:i',$v['create_time']);

                $v['update_time'] = date('m-d H:i',$v['update_time']);

            }

        }

        return $data;


    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-05 16:17
     * @功能说明:pptz转pdf
     */
    public function pptTopdf($ppt,$type=1){

        $path = MATER_UPLOAD_PATH.date('Y-m-d',time()).'/pdf';

        if (!file_exists($path)){

            mkdir ($path,0777,true);
        }


        $res = @exec("soffice --headless --invisible --convert-to pdf ".$ppt."  --outdir ".$path);

        $result = mb_substr($ppt,mb_strripos($ppt,'/')+1);

        $incom  =  mb_substr($result,mb_strripos($result,'.')+1);

        $result = str_replace($incom,'pdf',$result);

        $result = $path.'/'.$result;

        if(!file_exists($result)){

            return false;
        }

        if($type==1){

            $result = str_replace(FILE_UPLOAD_PATH,HTTPS_PATH,$result);
        }

        return $result;

    }





    /**
     * @author chenniang
     * @DataTime: 2021-07-05 16:16
     * @功能说明:pdf转图片
     */
    public function pdf2png($pdf)
    {
        $path = MATER_UPLOAD_PATH.date('Y-m-d',time()).'/img/';

        if (!file_exists($path)){

            mkdir ($path,0777,true);
        }

        if (!extension_loaded('imagick')) {

            return false;

        }

        if (!file_exists($pdf)) {

            return false;

        }

        $im = new \Imagick();

        $im->setResolution(100, 100); //设置分辨率 值越大分辨率越高

        $im->setCompressionQuality(20);

        $im->readImage($pdf);

        $http = 'https://'.$_SERVER['HTTP_HOST'].'/attachment/';

        foreach ($im as $k => $v) {

            $v->setImageFormat('jpg');

            $fileName = $path . md5($k . time()) . '.jpg';

            if ($v->writeImage($fileName) == true) {

                $fileName = str_replace(FILE_UPLOAD_PATH,$http,$fileName);

                $return[] = $fileName;

            }

        }

        return $return;

    }








}